#include<unistd.h>
#include"thread.h"
#include<sys/socket.h>
#include<sys/types.h>
#include<string.h>
#include"reactor.h"
#include"public.h"

    void* Thread::taskFunc(void*arg)
    {
        Thread*thread=static_cast<Thread*>(arg);
        thread->m_reactor=new Reactor();
        thread->m_reactor->AddEventAndHander(thread->GetSocketPairSecond(),EV_READ | EV_PERSIST,Thread::SocketPairEventCallBack,arg);
        LOG_INFO<<thread->GetTid();
        thread->m_reactor->Loop();
        return NULL;
    }


    void Thread::SocketPairEventCallBack(int fd,short events,void*arg)//用来处理主线程发送过来的cfd
    {
        Thread*thread=static_cast<Thread*>(arg);
        int cfd=0;
        if(read(fd,&cfd,4)<=0)
        {
            LOG_ERROR<<strerror(errno);
        }
        //client io
        thread->m_reactor->AddEventAndHander(cfd,EV_READ|EV_PERSIST,Thread::ClientIOEventCallBack,arg);
    }

    void Thread::ClientIOEventCallBack(int fd,short events,void*arg)//处理cfd上发生的i/o事件
    {
        char buf[LARGE_BUF_LEN]={0};
        if(read(fd,buf,LARGE_BUF_LEN)<=0)
        {
            LOG_INFO<<"client disconnected!";
        }
        LOG_INFO<<buf;

        //mvc+mysql+redis
    }

   
    Thread::Thread()
    {
        if(pthread_create(&m_tid,NULL,taskFunc,this))//创建任务线程
        {
            LOG_ERROR<<"创建线程失败！";
        }
        if(-1==socketpair(AF_UNIX,SOCK_STREAM,0,m_channle))//初始化任务线程和主线程进行通信的管道
        {
            LOG_ERROR<<strerror(errno);
        }   
    }

    Thread::~Thread()
    {
        pthread_join(m_tid,NULL);
    }

    int Thread::GetSocketPairFirst()const
    {
        return m_channle[0];
    }

    int Thread::GetSocketPairSecond()const
    {
        return m_channle[1];
    }

    pthread_t Thread::GetTid()const
    {
        return m_tid;
    } 

    // int main()
    // {
    //     Thread t;
    //     sleep(1);

    //     return 0;
    // }
    